import { DataTableColumns, NButton, NSpace, NSwitch, useDialog, useMessage } from 'naive-ui'
import { useI18n } from 'vue-i18n'

import { deleteRole, updateRoleStatus } from '@/apis'
import { RoleItem } from '@/apis/role/type/vo'
import CustomPopconfirm from '@/components/CustomPopconfirm.vue'
import { StatusEnum } from '@/types/enum/index'
import { catchToTuple } from '@/utils'

export function useTable({ modalShow, modalType, modalFormData, detailsShow, detailsData, init }: any) {
  const { t } = useI18n()
  const dialog = useDialog()
  const message = useMessage()

  // 加载中
  const loading = ref<boolean>(false)

  // 选中行
  const checkedRowKeys = ref<Array<number>>([])

  // 生成 columns 配置
  const columns = computed(
    (): DataTableColumns<RoleItem> => [
      {
        type: 'selection',
      },
      {
        title: 'id',
        key: 'id',
      },
      {
        title: t('role.key'),
        key: 'key',
        ellipsis: {
          tooltip: true,
        },
        render: (row: RoleItem) => row.key || '--',
      },
      {
        title: t('role.name'),
        key: 'name',
        ellipsis: {
          tooltip: true,
        },
        render: (row: RoleItem) => row.name || '--',
      },
      {
        title: t('common.sort'),
        key: 'sort',
        ellipsis: {
          tooltip: true,
        },
        render: (row: RoleItem) => row.sort || '--',
      },
      {
        title: t('common.status'),
        key: 'status',
        render(row: RoleItem) {
          return (
            <NSwitch
              checked-value={StatusEnum.DYNAMIC}
              unchecked-value={StatusEnum.STATIC}
              value={row.status}
              onUpdateValue={(status: StatusEnum) => changStatus({ row, status })}
            />
          )
        },
      },
      {
        title: t('common.create_time'),
        key: 'create_time',
        ellipsis: {
          tooltip: true,
        },
      },
      {
        title: t('common.update_time'),
        key: 'update_time',
        ellipsis: {
          tooltip: true,
        },
      },
      {
        title: t('common.action'),
        key: 'actions',
        width: 200,
        render(row: RoleItem) {
          return (
            <NSpace>
              <NButton type="info" size="small" text onClick={() => handleEditRole(row)}>
                {t('common.edit')}
              </NButton>
              <NButton type="info" size="small" text onClick={() => handleDetailRole(row)}>
                {t('common.detail')}
              </NButton>
              <CustomPopconfirm
                buttonType="error"
                gradientType="error"
                btnName={t('common.delete')}
                msg={t('common.deleteConfirm')}
                onHandle-submit={() => handleDeleteRole(row.id)}
              />
            </NSpace>
          )
        },
      },
    ],
  )

  // 生成 列表项 options 配置
  const checkboxOptions = computed(() =>
    columns.value.reduce<{ label: string; value: string }[]>((acc, column) => {
      if (column.type === 'selection') {
        acc.push({ label: t('common.selection'), value: 'selection' })
      }
      if ('title' in column && 'key' in column && typeof column.title === 'string' && typeof column.key === 'string') {
        if (column.key === 'actions') {
          acc.push({ label: t('common.action'), value: 'actions' })
        } else {
          acc.push({ label: column.title, value: column.key })
        }
      }
      return acc
    }, []),
  )

  // 当前选中项
  const checkedColumnsKeys = ref<string[]>(checkboxOptions.value.map((item) => item.value))

  // 根据当前选中项过滤出显示的列
  const filteredColumns = computed(() => {
    return columns.value.filter((column) => {
      if (checkedColumnsKeys.value.includes('selection') && column.type === 'selection') return column
      if ('key' in column && typeof column.key === 'string') return checkedColumnsKeys.value.includes(column.key)
      return false
    })
  })

  // 编辑
  const handleEditRole = (row: RoleItem) => {
    console.log('编辑', row)
    modalShow.value = true
    modalType.value = 'update'
    Object.assign(modalFormData.value, row)
  }

  // 删除
  const handleDeleteRole = async (ids: number | number[]) => {
    const [err, data] = await catchToTuple(deleteRole({ ids }))
    if (err) return
    if (data?.code === 200) {
      message.success(data.message)
      init()
    }
  }

  // 详情
  const handleDetailRole = (row: RoleItem) => {
    detailsShow.value = true
    Object.assign(detailsData.value, row)
  }

  // 添加
  const handleCreate = () => {
    modalShow.value = true
    modalType.value = 'create'
  }

  // 导出
  const handleExport = () => {
    dialog.warning({
      title: '确定导出全部用户?',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        console.log('确定')
      },
      onNegativeClick: () => {
        console.log('取消')
      },
    })
  }

  // 批量删除
  const handleDeleteBatch = () => {
    if (checkedRowKeys.value.length === 0) {
      return message.error('请选择要删除的数据')
    }
    dialog.error({
      title: '确定删除选中的数据?',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        console.log('确定')
        handleDeleteRole(checkedRowKeys.value)
      },
      onNegativeClick: () => {
        console.log('取消')
      },
    })
  }

  // 切换状态
  const changStatus = async ({ row, status }: { row: RoleItem; status: StatusEnum }) => {
    row.status = status
    const [err, data] = await catchToTuple(updateRoleStatus({ id: row.id, status }))
    if (err) return

    if (data?.code !== 200) {
      row.status = status === StatusEnum.DYNAMIC ? StatusEnum.STATIC : StatusEnum.DYNAMIC
    }

    if (data?.code === 200) {
      message.success(data.message)
    }
  }

  return {
    loading,
    checkedRowKeys,
    checkboxOptions,
    checkedColumnsKeys,
    filteredColumns,
    handleCreate,
    handleExport,
    handleDeleteBatch,
  }
}
